<template>
  <view class="home-page">
    <image src="/static/images/bg-index.png" class="bg-image" mode="widthFix"></image>
    <!-- 下拉刷新 -->
    <scroll-view 
      class="scroll-container" 
      scroll-y 
      refresher-enabled 
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
      @refresherrestore="onRestore"
    >
      <!-- Logo区域 -->
      <view class="logo-section">
        <image src="/static/logo.png" class="logo-img" mode="aspectFit"></image>
      </view>
      
      <!-- 搜索栏 -->
      <view class="search-section">
        <view class="search-container">
          <!-- 分类下拉 -->
          <view class="category-dropdown" @click="showCategoryPicker">
            <text class="category-text">{{ selectedCategory }}</text>
            <u-icon name="arrow-down" size="16" color="#666"></u-icon>
          </view>
          
          <!-- 搜索输入框 -->
          <view class="search-input-wrapper">
            <u-icon name="search" color="#999" size="20"></u-icon>
            <input 
              class="search-input" 
              v-model="searchKeyword" 
              placeholder="输入关键词"
              @confirm="handleSearch"
            />
          </view>
          
          <!-- 搜索按钮 -->
          <view class="search-btn" @click="handleSearch">
            <text class="search-btn-text">搜索</text>
          </view>
        </view>
      </view>
      
      <!-- 行情仅供参考区 -->
      <view class="market-section">
        <!-- 标题栏 -->
        <view class="market-header">
          <text class="market-title">行情仅供参考</text>
          <view class="platform-notice">
            <u-icon name="info-circle" size="16" color="#fff"></u-icon>
            <text class="notice-text">本站非交易平台</text>
          </view>
        </view>
        
        <!-- 商品列表区 - 白色背景，向上滚动 -->
        <view class="market-list-container">
          <swiper class="market-swiper" vertical circular autoplay :interval="3500" :duration="1500">
            <swiper-item v-for="(slide, sIndex) in marketSlides" :key="sIndex">
              <view class="market-list">
                <view 
                  class="market-item" 
                  v-for="(item, index) in slide" 
                  :key="index"
                  @tap="handleMarketItemTap(item)" 
                  @click="handleMarketItemTap(item)"
                >
                  <text class="product-name">{{ item.name || item.product_name }}</text>
                  <view class="price-info" :class="item.change_rate > 0 ? 'price-up-color' : (item.change_rate < 0 ? 'price-down-color' : 'price-flat-color')">
                    <text class="product-price">{{ formatPrice(item.market_price) }}</text>
                    <text class="price-change" :class="item.change_rate > 0 ? 'price-up' : (item.change_rate < 0 ? 'price-down' : 'price-flat')">
                      {{ formatChange(item.change_rate) }}
                    </text>
                  </view>
                </view>
              </view>
            </swiper-item>
          </swiper>
        </view>
        
        <!-- 平台公告栏 - 官方推荐swiper滚动，避免滚动条 -->
        <view class="announcement-bar" v-if="announcementsData.length > 0">
          <swiper 
            class="announcement-swiper" 
            :autoplay="true" 
            :interval="4000" 
            :duration="500" 
            :circular="true" 
            :indicator-dots="false"
          >
            <swiper-item 
              v-for="(item, index) in announcementsData" 
              :key="index"
              @click="handleAnnouncementTap(item.id)"
            >
              <view class="announcement-item">
                <u-icon name="bell" size="16" color="#fff" class="announcement-item-icon"></u-icon>
                <text class="announcement-text">{{ item.title }}</text>
              </view>
            </swiper-item>
          </swiper>
          <u-icon name="arrow-right" size="16" color="#fff"></u-icon>
        </view>
      </view>
      
      <!-- 广告横幅 - 左右滚动 -->
      <view class="advertisement-section" v-if="bannerAds.length > 0">
        <swiper 
          class="ad-swiper" 
          :indicator-dots="true" 
          :autoplay="true" 
          :interval="4000" 
          :duration="500"
          indicator-color="rgba(255,255,255,0.5)"
          indicator-active-color="#fff"
        >
          <swiper-item v-for="(ad, index) in bannerAds" :key="index" @click="handleAdClick(ad)">
            <image 
              :src="PICTURE_URL + ad.cover_url" 
              class="ad-image" 
              mode="aspectFill"
            ></image>
          </swiper-item>
        </swiper>
      </view>
      
      <!-- 快捷功能栏 -->
      <view class="quick-functions">
        <text class="section-title">快捷功能</text>
        
        <!-- 第一行：今日行情、酒水行情、茶叶行情 -->
        <view class="function-row">
          <view class="function-item" @click="goToList('tobacco')">
            <view class="function-icon today-quotes">
              <image src="/static/images/function-today-quotes.png" mode="aspectFit" class="function-image"></image>
            </view>
            <text class="function-label">今日行情</text>
          </view>
          
          <view class="function-item" @click="goToList('alcohol')">
            <view class="function-icon wine-quotes">
              <image src="/static/images/function-wine-quotes.png" mode="aspectFit" class="function-image"></image>
            </view>
            <text class="function-label">酒水行情</text>
          </view>
          
          <view class="function-item" @click="goToList('tea')">
            <view class="function-icon tea-quotes">
              <image src="/static/images/function-tea-quotes.png" mode="aspectFit" class="function-image"></image>
            </view>
            <text class="function-label">茶叶行情</text>
          </view>
        </view>
        
        <!-- 第二行：真假辨别、会员认证 -->
        <view class="function-row">
          <view class="function-item" @click="goToAuthenticate">
            <view class="function-icon authenticate">
              <image src="/static/images/function-authenticate.png" mode="aspectFit" class="function-image"></image>
            </view>
            <text class="function-label">真假辨别</text>
          </view>
          
          <view class="function-item" @click="goToVip">
            <view class="function-icon vip">
              <image src="/static/images/function-vip.png" mode="aspectFit" class="function-image"></image>
            </view>
            <text class="function-label">会员认证</text>
          </view>
          
          <!-- 占位空白 -->
          <view class="function-item function-placeholder"></view>
        </view>
      </view>
    </scroll-view>
    
    <!-- 分类选择器 -->
    <u-picker
      :show="showPicker"
      :columns="categoryColumns"
      @confirm="onCategoryConfirm"
      @cancel="showPicker = false"
    ></u-picker>
  </view>
</template>

<script>
/**
 * 首页
 * @author 王勇程 <laughskydragon@qq.com>
 */
import { productApi, advertisementApi, announcementApi, combinationApi } from '@/api'
import { handleError } from '@/utils/common'
import config from '@/config/index' // 导入API基础地址配置

export default {
  data() {
    return {
      // 搜索相关
      searchKeyword: '',
      selectedCategory: '口粮',
      showPicker: false,
      categoryColumns: [
        ['口粮', '酒', '茶']
      ],
      
      // 下拉刷新
      refreshing: false,
      
      // 市场数据
      marketData: [],
      
      // 公告数据
      announcementText: '平台公告（左右滑动）可查看详情...',
      announcementsData: [],
      
      // 广告数据
      bannerAds: [],
      
      // 加载状态
      isLoading: false,
      PICTURE_URL: config.BASE_URL + '/upload/picture/' // 暴露BASE_URL到data中
    }
  },
  computed: {
    marketSlides() {
      const arr = this.marketData || []
      const size = 10
      const slides = []
      for (let i = 0; i < arr.length; i += size) {
        slides.push(arr.slice(i, i + size))
      }
      return slides
    }
  },
  
  onLoad(options) {
    this.loadHomeData()
    this.checkInviteId(options)
  },
  
  onShow() {
    this.loadHomeData()
  },
  
  onUnload() {
    this.stopAnnouncementScroll()
  },
  
  methods: {
    checkInviteId(options = {}) {
      try {
        const rawScene = options && options.scene ? decodeURIComponent(options.scene) : ''
        let inviterId = 0
        if (rawScene) {
          const m = rawScene.match(/(?:^|[&?])inviter_id=(\d+)/)
          if (m) inviterId = parseInt(m[1], 10)
        }
        if (!inviterId && options && options.inviter_id) {
          inviterId = parseInt(options.inviter_id, 10)
        }
        if (!inviterId && options && options.code) {
          const codeStr = String(options.code)
          const mm = codeStr.match(/(?:^|[&?])inviter_id=(\d+)/)
          inviterId = mm ? parseInt(mm[1], 10) : parseInt(codeStr, 10)
        }
        if (!inviterId || inviterId <= 0) return
        uni.setStorageSync('pending_inviter_id', inviterId)
      } catch (e) {}
    },
    // 加载首页聚合数据
    async loadHomeData() {
      if (this.isLoading) return
      
      try {
        this.isLoading = true
        // 调用聚合API获取所有首页数据
        const result = await combinationApi.getHomePageData()
        console.log('聚合数据:', result)
        if (result) {
          console.log('商品数据:', result.hot_products.data)
          this.marketData = result.hot_products.data || [] // 适配新数据结构：提取data下的商品列表
          this.bannerAds = result.advertisements.data || [] // 适配新数据结构：提取data下的广告列表
          this.announcementsData = result.announcements.data || [] // 将公告列表赋值给announcementsData
          this.announcementText = '平台公告（左右滑动）可查看详情...' // 保持默认文本
          console.log('公告数据:', this.announcementsData)
        }
      } catch (error) {
        console.error('加载首页数据失败:', error)
        handleError(error, '加载数据失败')
      } finally {
        this.isLoading = false
      }
    },
    
    // 下拉刷新
    async onRefresh() {
      this.refreshing = true
      await this.loadHomeData()
    },
    
    // 刷新恢复
    onRestore() {
      this.refreshing = false
    },
    
    
    // swiper自动滚动，无需手动计时器
    
    // 显示分类选择器
    showCategoryPicker() {
      this.showPicker = true
    },
    
    // 分类选择确认
    onCategoryConfirm(value) {
      this.selectedCategory = value[0]
      this.showPicker = false
    },
    getCategoryCode(label) {
      const map = {
        '全部': '',
        '口粮': 'tobacco',
        '酒': 'alcohol',
        '茶': 'tea'
      }
      return map[label] ?? ''
    },
    
    // 处理搜索
    handleSearch() {
      if (!this.searchKeyword.trim()) {
        uni.showToast({
          title: '请输入搜索关键词',
          icon: 'none'
        })
        return
      }
      
      uni.navigateTo({
        url: `/pages/product/list?keyword=${encodeURIComponent(this.searchKeyword)}&category=${encodeURIComponent(this.getCategoryCode(this.selectedCategory))}`
      })
    },
    
    // 跳转到行情页面
    goToList(type = 'all') {
      uni.navigateTo({
        url: `/pages/product/list?category=` + type
      })
    },
    
    // 跳转到真假辨别（文章id=6）
    goToAuthenticate() {
      uni.navigateTo({
        url: '/pages/article/detail?id=6'
      })
    },
    
    // 跳转到VIP认证
    goToVip() {
      uni.navigateTo({
        url: '/pages/user/vip/index'
      })
    },
    
    // 跳转到商品详情
    goToProductDetail(product) {
      if (!product || !product.id) {
        uni.showToast({
          title: '商品信息错误',
          icon: 'none'
        })
        return
      }
      
      uni.navigateTo({
        url: `/pages/product/detail?id=${product.id}`
      })
    },
    
    // 查看公告详情
    viewAnnouncementDetail(id) {
      uni.navigateTo({
        url: `/pages/announcement/announcement?id=${id}`
      })
    },

    
    handleMarketItemTap(item) {
      this.goToProductDetail(item)
    },
    handleAnnouncementTap(id) {
      this.viewAnnouncementDetail(id)
    },
    
    // 处理广告点击
    async handleAdClick(ad) {
      return;
      try {
        // 记录点击
        await advertisementApi.recordAdvertisementLog({
          ad_id: ad.id,
          action: 'click'
        })
        
        // 跳转链接
        if (ad.link_url) {
          if (ad.link_type === 'page') {
            uni.navigateTo({
              url: ad.link_url
            })
          } else if (ad.link_type === 'web') {
            // 打开外部链接
            uni.navigateTo({
              url: `/pages/webview/webview?url=${encodeURIComponent(ad.link_url)}`
            })
          }
        }
      } catch (error) {
        console.error('处理广告点击失败:', error)
      }
    },
    
    // 格式化价格
    formatPrice(price) {
      const numPrice = parseFloat(price || 0)
      return numPrice.toFixed(1)
    },
    
    // 格式化涨跌
    formatChange(change) {
      const changeValue = parseFloat(change || 0)
      if (changeValue > 0) {
        return `+${changeValue.toFixed(1)}`
      } else if (changeValue < 0) {
        return changeValue.toFixed(1)
      } else {
        return '0.0'
      }
    },

  }
}
</script>

<style scoped>
/* 页面容器 */
.home-page {
      min-height: 100vh;
      background-color: #f4f3f8;
      position: relative; /* 确保背景图片定位正确 */
}

.bg-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: auto;
}

.scroll-container {
  height: 100vh;
}

/* Logo区域 */
.logo-section {
  margin-top: var(--status-bar-height);
  padding: 60rpx 20rpx 0;
}

.logo-img {
  width: 168rpx;
  height: 42rpx;
}

/* 搜索区域 */
.search-section {
  padding: 0 20rpx;
  margin: 20rpx 0;
}

.search-container {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 50rpx;
  overflow: hidden;
}

.category-dropdown {
  display: flex;
  align-items: center;
  margin: 20rpx 0;
  padding: 0 20rpx;
  height: 50rpx;
  border-right: 2rpx solid #e0e0e0;
  background: #FFF;
}

.category-text {
  font-size: 28rpx;
  color: #333;
  margin-right: 8rpx;
  white-space: nowrap;
}

.search-input-wrapper {
  flex: 1;
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 30px;
  padding: 5px 15px;
  margin-right: 10px;
}

.search-input {
  flex: 1;
  height: 36px;
  line-height: 36px;
  font-size: 14px;
  color: #333;
  margin-left: 10px; /* 给图标留出空间 */
}

.search-btn {
  background: #FFF;
  height: 80rpx;
  padding: 0 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-btn-text {
  color: #fd6f73;
  font-size: 28rpx;
  font-weight: 500;
}

/* 行情区域 */
.market-section {
  margin: 0 20rpx 20rpx;
  border-radius: 10rpx;
  background: linear-gradient(to bottom, #fe444e 0%, #fc7981 100%);
  overflow: hidden;
}

.market-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
}

.market-title {
  font-size: 30rpx;
  color: #fff;
}

.platform-notice {
  display: flex;
  align-items: center;
}

.notice-text {
  font-size: 28rpx;
  color: #fff;
  margin-left: 8rpx;
  font-weight: lighter;
}

/* 商品列表区域 */
.market-list-container {
  background: #fff;
  margin: 0 10rpx;
  border-radius: 15rpx;
  height: 450rpx;
  overflow: hidden;
}

.market-scroll {
  height: 100%;
}

.market-list {
  display: flex;
  flex-wrap: wrap;
  padding: 10rpx;
}

.market-item {
  width: 50%;
  display: flex;
  justify-content: space-between; /* 商品名称和价格信息两端对齐 */
  align-items: center;
  padding: 25rpx 10rpx;
  box-sizing: border-box;
}

.market-item:nth-child(2n) {
  border-right: none;
}

.market-item:nth-last-child(1),
.market-item:nth-last-child(2) {
  border-bottom: none;
}

.product-name {
  font-size: 28rpx;
  color: #111;
  font-weight: bold;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 180rpx; /* 限制商品名称宽度 */
}

.price-info {
  display: flex;
  align-items: center;
}

.product-price {
  font-size: 24rpx;
  font-weight: bold;
  margin-right: 10rpx;
}

.price-change {
  font-size: 24rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.price-change::before {
  font-family: 'uicon-iconfont'; /* 假设uView的图标字体 */
  margin-right: 4rpx;
}

.price-up::before {
  content: '↑'; /* 向上箭头图标 */
}

.price-down::before {
  content: '↓'; /* 向下箭头图标 */
}

.price-flat::before {
  content: '-'; /* 减号 */
}

.price-up-color {
  color: #ea4148;
}

.price-down-color {
  color: #67c58a;
}

.price-flat-color {
  color: #ea4148;
}

/* 公告栏 */
.announcement-bar {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  margin-top: 20rpx;
}

.announcement-icon {
  margin-right: 15rpx;
}

.announcement-scroll {
  flex: 1;
  white-space: nowrap; /* 确保内容不换行 */
  overflow: hidden; /* 隐藏超出部分 */
  margin-right: 15rpx;
}

/* 使用swiper滚动公告，避免出现滚动条 */
.announcement-swiper {
  flex: 1;
  height: 60rpx;
}

.announcement-list {
  display: flex; /* 使用flex布局使子项横向排列 */
  align-items: center;
}

.announcement-item {
  display: flex; /* 使用flex布局使子项横向排列 */
  align-items: center;
  margin-right: 30rpx; /* 公告标题之间的间距 */
}

.announcement-text {
  font-size: 26rpx;
  color: #fff;
  white-space: nowrap;}

/* 广告区域 */
.advertisement-section {
  margin: 0 20rpx 30rpx;
}

.ad-swiper {
  height: 200rpx;
  border-radius: 15rpx;
  overflow: hidden;
}

.ad-image {
  width: 100%;
  height: 100%;
}

/* 市场列表滚动区 */
.market-swiper {
  height: 450rpx;
}

/* 快捷功能区 */
.quick-functions {
  margin: 0 30rpx 50rpx;
  padding-bottom: 100rpx;
}

.section-title {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 30rpx;
  display: block;
}

.function-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 40rpx;
}

.function-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 15rpx;
  background-color: #FFF;
  padding: 20rpx;
  border-radius: 15rpx;
  box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.1);
}

.function-placeholder {
  opacity: 0;
}

.function-icon {
  width: 120rpx;
  height: 120rpx;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 15rpx;
}

.function-label {
  font-size: 26rpx;
  color: #333;
  text-align: center;
}

.function-image {
  width: 100%;
  height: 100%;
}
</style>
